import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Spin, Alert, Button } from 'antd';
import { 
  ReloadOutlined, 
  EyeOutlined, 
  BarChartOutlined,
  CloudOutlined,
  HeartOutlined,
  CarOutlined,
  DatabaseOutlined
} from '@ant-design/icons';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { apiService } from '../services/apiService';
import './Dashboard.css';

interface DashboardData {
  [key: string]: {
    data: any;
    last_updated: string;
    source_name: string;
  };
}

interface DashboardStats {
  data_sources: {
    total: number;
    active: number;
    inactive: number;
  };
  data_records: {
    total: number;
    today: number;
    last_24h: number;
  };
  data_type_distribution: {
    [key: string]: number;
  };
}

const Dashboard: React.FC = () => {
  const [dashboardData, setDashboardData] = useState<DashboardData>({});
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const [dataResponse, statsResponse] = await Promise.all([
        apiService.get('/api/dashboard/'),
        apiService.get('/api/dashboard/stats')
      ]);

      if (dataResponse.success) {
        setDashboardData(dataResponse.data);
      }

      if (statsResponse.success) {
        setStats(statsResponse.stats);
      }
    } catch (err) {
      setError('获取仪表盘数据失败');
      console.error('Dashboard data fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDashboardData();
    
    // 设置定时刷新
    const interval = setInterval(fetchDashboardData, 30000); // 30秒刷新一次
    
    return () => clearInterval(interval);
  }, []);

  const getDataIcon = (dataType: string) => {
    const icons: { [key: string]: React.ReactNode } = {
      weather: <CloudOutlined />,
      covid: <HeartOutlined />,
      flu: <HeartOutlined />,
      traffic: <CarOutlined />,
      air_quality: <CloudOutlined />,
      economic: <BarChartOutlined />
    };
    return icons[dataType] || <BarChartOutlined />;
  };

  const getDataColor = (dataType: string) => {
    const colors: { [key: string]: string } = {
      weather: '#1890ff',
      covid: '#ff4d4f',
      flu: '#fa8c16',
      traffic: '#52c41a',
      air_quality: '#722ed1',
      economic: '#13c2c2'
    };
    return colors[dataType] || '#1890ff';
  };

  if (loading) {
    return (
      <div className="dashboard-loading">
        <Spin size="large" />
        <p>加载仪表盘数据中...</p>
      </div>
    );
  }

  return (
    <div className="dashboard-container page-transition">
      <div className="dashboard-header">
        <h1>📊 数据仪表盘</h1>
        <Button 
          type="primary" 
          icon={<ReloadOutlined />} 
          onClick={fetchDashboardData}
          loading={loading}
        >
          刷新数据
        </Button>
      </div>

      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 统计卡片 */}
      {stats && (
        <Row gutter={[16, 16]} className="stats-row">
          <Col xs={24} sm={12} lg={6}>
            <Card className="stat-card">
              <Statistic
                title="数据源总数"
                value={stats.data_sources.total}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card className="stat-card">
              <Statistic
                title="活跃数据源"
                value={stats.data_sources.active}
                prefix={<EyeOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card className="stat-card">
              <Statistic
                title="今日数据记录"
                value={stats.data_records.today}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card className="stat-card">
              <Statistic
                title="24小时数据量"
                value={stats.data_records.last_24h}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 数据源卡片 */}
      <Row gutter={[16, 16]} className="data-sources-row">
        {Object.entries(dashboardData).map(([dataType, data]) => (
          <Col xs={24} sm={12} lg={8} key={dataType}>
            <Card 
              className="data-source-card hover-shadow"
              title={
                <div className="card-title">
                  {getDataIcon(dataType)}
                  <span>{data.source_name}</span>
                </div>
              }
              extra={
                <span className="last-updated">
                  更新: {new Date(data.last_updated).toLocaleString()}
                </span>
              }
            >
              <div className="data-content">
                <div className="data-summary">
                  <h4>数据类型: {dataType}</h4>
                  <p>数据点数量: {Object.keys(data.data).length}</p>
                </div>
                <div className="data-preview">
                  <pre>{JSON.stringify(data.data, null, 2).substring(0, 200)}...</pre>
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 数据分布图表 */}
      {stats && stats.data_type_distribution && (
        <Card title="数据分布" className="chart-card">
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={Object.entries(stats.data_type_distribution).map(([type, count]) => ({
              type,
              count
            }))}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="type" />
              <YAxis />
              <Tooltip />
              <Line 
                type="monotone" 
                dataKey="count" 
                stroke="#1890ff" 
                strokeWidth={2}
                dot={{ fill: '#1890ff', strokeWidth: 2, r: 4 }}
              />
            </LineChart>
          </ResponsiveContainer>
        </Card>
      )}
    </div>
  );
};

export default Dashboard;
